﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SO_DataFetcher.PubFunctions.DataLink;
using SO_DataFetcher.PubFunctions.SqlScripts;

namespace SO_DataFetcher.PubFunctions.Actions
{
    public class PubAction
    {
        public static Dictionary<string, ActionStruct> Actions = new Dictionary<string, ActionStruct>();    //公共字典集
        public static DataSet DatasetActions = null;    //公共数据集  
        public static DataTable DataTableActions = new DataTable();
        private static readonly string XmlPath = PubCommon.XmlActionsPath;

        public static Dictionary<string, ActionStruct> ActionList = new Dictionary<string, ActionStruct>(); //需要处理的动作

        private static bool _isXmlExist = false;

        /// <summary>
        /// 初始化动作
        /// </summary>
        public static void Init()
        {
            try
            {
                IsXmlExist();

                if (_isXmlExist)
                    GetTableActions();
                else
                {
                    DataTableActions = new DataTable();
                    DataTableActions.Columns.Add("Index", typeof(string));
                    DataTableActions.Columns.Add("Name", typeof(string));
                    DataTableActions.Columns.Add("DataLink", typeof(string));
                    DataTableActions.Columns.Add("SQL", typeof(string));
                    DataTableActions.Columns.Add("OutPath", typeof(string));
                }
                PubLog.WriteLog("初始化动作配置文件完成");
            }
            catch (Exception ex)
            {
                PubLog.WriteLog("初始化动作配置文件错误：" + ex.Message);
            }
        }

        public static void IsXmlExist()
        {
            _isXmlExist = File.Exists(XmlPath);
        }

        /// <summary>                                                       
        /// 更新连接数据
        /// </summary>                                                     
        private static void GetTableActions()   
        {
            DatasetActions = PubXml.GetDataSetFromXml(XmlPath);

            if (DatasetActions.Tables.Count > 0)
            {
                DataTableActions = DatasetActions.Tables[0];

                if (DataTableActions != null && DataTableActions.Rows.Count > 0)
                    GetDictionaryActions();
            }
        }

        /// <summary>
        /// 存储为字典变量
        /// </summary>
        private static void GetDictionaryActions()      
        {
            Actions = new Dictionary<string, ActionStruct>();

            foreach (DataRow dataRow in DataTableActions.Rows)
            {

                string index = dataRow["Index"].ToString();
                string name = dataRow["Name"].ToString();
                string datalink = dataRow["DataLink"].ToString();
                string sql = dataRow["SQL"].ToString();
                string outpath = dataRow["OutPath"].ToString();

                var actionStruct = new ActionStruct
                {
                    Index = index,     
                    Name = name,
                    DataLink = datalink,
                    Sql = sql,
                    OutPath = outpath
                };

                Actions.Add(index, actionStruct);
            }
        }

        /// <summary>
        /// 保存修改后的dataset到xml文件中
        /// </summary>
        public static void SaveDataSetActions() 
        {
            if (DatasetActions != null)
            {
                DatasetActions.Tables.Clear();
                DatasetActions.Tables.Add(DataTableActions);
                GetDictionaryActions();
                XmlUtility.SaveXmlSetting(DatasetActions, XmlPath);
                IsXmlExist();
            }
        }

        /// <summary>
        /// 处理动作列表
        /// </summary>
        public static void DoActions()
        {
            if (ActionList.Count < 1)
            {
                MessageBox.Show(@"没有选择任何动作，请选择后再执行。");
                return;
            }

            PubControls.ProgressBarToolStrip.Maximum = ActionList.Count;
            PubControls.ProgressBarToolStrip.Value = 0;

            foreach (KeyValuePair<string, ActionStruct> keyValuePair in ActionList)
            {
                string key = keyValuePair.Key;

                PubLog.WriteLog(@"正在执行动作: " + key);
                PubControls.LabelToolStatus.Text = @"正在执行动作: " + key;

                try
                {
                    ActionStruct actionStruct = keyValuePair.Value;

                    DataTable dataTable = GetCurrentActionTable(actionStruct);

                    string fileName = PubCommon.MainPath + @"\" + actionStruct.Name + ".csv";

                    string outPath = actionStruct.OutPath;
                    if (!string.IsNullOrEmpty(outPath))
                        if (Directory.Exists(outPath))
                            fileName = outPath + @"\" + actionStruct.Name + ".csv";

                    if (!string.IsNullOrEmpty(fileName) && dataTable != null)
                        PubCsv.ExportCsv(fileName, dataTable);

                    PubLog.WriteLog(@"动作: " + key + " 执行完成.");

                    SetDoColor(key, Color.Green);
                }
                catch (Exception exception)
                {
                    PubLog.WriteLog(@"执行动作: "+ key +" 时出错，此动作无法完成."+ exception.Message);
                    SetDoColor(key, Color.Red);
                }

                PubControls.ProgressBarToolStrip.Value = PubControls.ProgressBarToolStrip.Value + 1;
            }

            PubControls.LabelToolStatus.Text = @"执行完成";
            PubControls.ProgressBarToolStrip.Value = PubControls.ProgressBarToolStrip.Maximum;
        }

        public static void SetDoColor(string index, Color backColor)
        {
            foreach (DataGridViewRow dataGridViewRow in PubControls.DataGridViewActions.Rows)
            {
                if (dataGridViewRow.Cells[0].Value.Equals(index))
                {
                    dataGridViewRow.Cells[PubControls.DataGridViewActions.ColumnCount - 1].Style.BackColor = backColor;

                    bool isChecked =  backColor != Color.Green;

                    dataGridViewRow.Cells[PubControls.DataGridViewActions.ColumnCount - 1].Value = isChecked;
                       
                    break;
                }
            }
        }

        /// <summary>
        /// 根据动作获取当前Table
        /// </summary>
        /// <param name="actionStruct"></param>
        /// <returns></returns>
        private static DataTable GetCurrentActionTable(ActionStruct actionStruct)
        {
            DataTable dataTable = null;

            try
            {
                string index = actionStruct.Index;
                string name = actionStruct.Name;

                string[] tempsqlscripts = actionStruct.Sql.Split(',');

                string[] sqls = PubScripts.SetSqlCurrentScripts(tempsqlscripts);

                string dataLink = actionStruct.DataLink;
                dataTable = PubDataLinks.GetCurrentActionTable(sqls, dataLink);

            }
            catch (Exception exception)
            {
                throw;
            }

            return dataTable;
        }
    }
}
